<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="考场名称" prop="roomName">
        <el-input v-model="queryParams.roomName" placeholder="请输入考场名称" clearable style="width: 200px" />
      </el-form-item>
      <!-- <el-form-item label="关联考试" prop="typeName">
        <el-select multiple v-model="form.libIds" placeholder="请选择">
          <el-option
            v-for="dict in knowList"
            :key="dict.libId"
            :label="dict.libTitle"
            :value="dict.libId"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="机位数量" prop="roomMachineCount">
        <el-input v-model="queryParams.roomMachineCount" placeholder="请输入机位数量" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item>
        <el-button color="#265DA4" :dark="isDark" icon="Search" @click="handleQuery" v-hasPermi="['manager:examinationRoom:query']">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button color="#265DA4" plain icon="Plus" @click="handleAdd" v-hasPermi="['manager:examinationRoom:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="left" type="index" width="100" />
      <el-table-column label="考场名称" align="left" prop="roomName" />
      <el-table-column label="考场地址" align="left" prop="roomAddress" />
      <el-table-column label="开放时间" align="left" prop="roomOpeningHours" />
      <el-table-column label="机位数量" align="left" prop="roomMachineCount" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link style="color:#265DA4;" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:examinationRoom:edit']">编辑</el-button>
          <el-button link style="color:#265DA4;" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manager:examinationRoom:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>{{ title }}</span>
      </template>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="考场名称:" prop="roomName">
              <el-input v-model="form.roomName" placeholder="请输入考点名称" class="inputDeep" />
            </el-form-item>
            <el-form-item label="考场地址:" prop="roomAddress">
              <div class="time-box">
                <el-input v-model="form.roomAddress" placeholder="请输入考点名称" class="inputDeep" />
                <el-button color="#265DA4" @click="selectAddress">选择</el-button>
              </div>
            </el-form-item>
            <el-form-item label="开放时间:" prop="libIds">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm" type="datetimerange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"></el-date-picker>
            </el-form-item>
            <el-form-item label="机位数量:" prop="roomMachineCount">
              <el-input v-model="form.roomMachineCount" type="number" min="0" placeholder="请输入" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图选择 -->
    <el-dialog title="考场地址" v-model="openMap" width="780px" append-to-body>
      <el-col :span="10">
        <div class="inputBox">
          <span>考场地址：</span>
          <input id="tipinput" placeholder="请输入地址查询" />
        </div>
      </el-col>
      <div id="container"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitMap">确 定</el-button>
          <el-button @click="cancelMap">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Place">
import AMapLoader from "@amap/amap-jsapi-loader";
import {
  examRoomList,
  examRoomAdd,
  examRoomEdit,
  examRoomDelete,
} from "@/api/examRoom/examConfig";
import { knowledgeLibraryList } from "@/api/knowledge/library";
import { onMounted } from "vue";
const { proxy } = getCurrentInstance();

const dateRange = ref([]);
const examList = ref([]);
const open = ref(false);
const openMap = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const mapValue = ref("");
const knowList = ref([]);
const mapAddressList = ref({});

const data = reactive({
  form: {
  },
  queryParams: {
    pageSize: 10,
    pageNum: 1,
    roomName: '',
    roomMachineCount: "",
  },
  rules: {
    roomName: [
      { required: true, message: "考场名称不能为空", trigger: "blur" },
    ],
    roomAddress: [
      { required: true, message: "考场地址不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

console.log(queryParams.value, "value");
/** 查询考点列表 */
function getList() {
  loading.value = true;
  examRoomList(queryParams.value).then((response) => {
    examList.value = response.rows;

    total.value = response.total;
    loading.value = false;
  });
}
/** 查询考点列表 */
function getLibraryList() {
  loading.value = true;
  knowledgeLibraryList({
    pageSize: 200,
    pageNum: 1,
  }).then((response) => {
    knowList.value = response.rows;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  dateRange.value = [];
  reset();
}
/** 表单重置 */
function reset() {

  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  dateRange.value = [];
  form.value.roomName = '';
  form.value.roomAddress = '';
  form.value.roomLongitude = '';
  form.value.roomLatitude = ''
  form.value.roomMachineCount = ''
  title.value = "新增";

}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  console.log(row, "f");
  open.value = true;
  title.value = "编辑";
  form.value.roomName = row.roomName;
  form.value.roomAddress = row.roomAddress;
  form.value.roomLongitude = row.roomLongitude;
  form.value.roomLatitude = row.roomLatitude
  form.value.roomMachineCount = row.roomMachineCount
  form.value.roomId = row.roomId
  dateRange.value = row.roomOpeningHours.split('~')
  console.log(dateRange.value, 'dateRange.value', row.roomOpeningHours);
}
/** 提交按钮 */
function submitForm() {
  console.log(form.value, "form.value");
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (form.value.roomId != undefined) {
        examRoomEdit({
          ...form.value,

        }).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        console.log(form.value, "form.value.", dateRange.value.join("~"));
        examRoomAdd({
          ...form.value,
          roomOpeningHours: dateRange.value.join("~"),
        }).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除"' + row.roomName + '"的数据项？')
    .then(function () {
      return examRoomDelete(row.roomId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
function selectAddress() {
  openMap.value = true;
  nextTick(() => {
    initMap()
    // ininMap1()
  });
}

// 地图选择
function submitMap() {
  openMap.value = false
  console.log(mapAddressList.value, 'mapAddressList.value');
  form.value.roomAddress = mapAddressList.value.name
  form.value.roomLongitude = mapAddressList.value.roomLongitude
  form.value.roomLatitude = mapAddressList.value.roomLatitude
}
function cancelMap() {
  openMap.value = false;
}

function initMap() {
  var map = new AMap.Map("container", {
    resizeEnable: true, //是否监控地图容器尺寸变化
    zoom: 11, //初始化地图层级
    city: '杭州',
    // center: [116.397428, 39.90923], //初始化地图中心点
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch"],
  });

  //输入提示
  // var autoOptions = {
  //       input: "tipinput"
  //   };

    // AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
    //     var auto = new AMap.AutoComplete(autoOptions);
    //     var placeSearch = new AMap.PlaceSearch({
    //         map: map
    //     });  //构造地点查询类
    //     auto.on("select", select);//注册监听，当选中某条记录时会触发
    //     function select(e) {
    //       console.log(e,'eeee');
    //         placeSearch.setCity(e.poi.adcode);
    //         placeSearch.search(e.poi.name);  //关键字查询查询
    //     }
    // });


  //输入提示
  AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
    var autoOptions = {
      input: "tipinput",
    };
    var auto = new AMap.Autocomplete(autoOptions);
    const placeSearch = new AMap.PlaceSearch({
      map: map
    })
    const geocoder = new AMap.Geocoder({
      radius: 1000,
      extensions: "all",
    });
    //构造地点查询类
    console.log(auto, 'auto1', proxy.$refs);
    AMap.event.addListener(auto, "select", function (data) {
      console.log(data, "data");
      let { poi } = data
      mapAddressList.value = {
        name: poi.name,
        roomLongitude: poi.location.lat,
        roomLatitude: poi.location.lng
      }

      placeSearch.search(placeSearch, function (status, result) {
        // 搜索成功时，result即是对应的匹配数据
        console.log(result, "result", status);
      });
      placeSearch.setCity(data.poi.adcode);
      placeSearch.search(data.poi.name); //关键字查询查询
    }); //注册监听，当选中某条记录时会触发
  });
}

getLibraryList();
getList();
</script>
<style lang="scss" scoped>
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #265DA4 !important; //修改默认的背景色
}
.amap-sug-result {
  z-index: 9999 !important;
}
</style>
<style lang="scss" scoped>
.inputDeep {
  :deep(.el-input__inner) {
    width: 186px !important;
  }
}

.time-box {
  display: flex;
  justify-content: space-between;

  .el-date-editor {
    width: 206px;
  }

  .el-button {
    margin-left: 15px;
  }
}

.inputBox {
  height: 50px;
  line-height: 30px;
  display: flex;
  width: 500px;

  input {
    border: 1px solid #d3d3d3;
    width: 400px;
    height: 30px;
    padding: 4px;
    outline: none;
    border-radius: 4px;
  }
}

#container {
  width: 100%;
  height: 400px;
}
</style>
